const osubmit = document.getElementById("submit");
const otel = document.getElementById("logon_id");
const opassword = document.getElementById("password");
osubmit.onclick = function(){
    // 发起ajax，请求登录功能，携带了用户名和密码
    ajax("http://localhost:3000/api",{
        type:"login",
        username:otel.value,
        password:opassword.value
    }).then(res=>{
        // 成功
        res = JSON.parse(res);
        // console.log(res);
        if(res.code === 1){
            // 登录成功后存储用户信息
            localStorage.setItem("username", res.data.username);
            // 登录成功后存储登录状态
            localStorage.setItem("isLogin", "ok");
            
            if(confirm("登录成功，是否跳转到首页")){
                location.href = "./index.html";
            }
        }else if(res.code === 0){
            // 用户名不存在
            if(confirm("用户名不存在，是否跳转到注册")){
                location.href = "./register.html";
            }
        }else if(res.code === 2){
            // 密码不对
            alert(res.title);
            opassword.value = "";
            opassword.focus();
        }
    },code=>{
        // 失败
        console.log(code);
    })
}


function ajax(url, data){
    let str = "";
    for(let i in data){
        str += `${i}=${data[i]}&`
    }
    url += "?" + str;

    const xhr = new XMLHttpRequest();
    xhr.open("get", url);
    xhr.send();

    return new Promise((resolve,reject)=>{
        xhr.onload = function(){
            if(xhr.status === 200){
                resolve(xhr.responseText);
            }else{
                reject(xhr.status);
            }
        }
    })
}
